var crypto = require("crypto");
var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var user = require("../model/user");
var essay = require("../model/essay");

//设置每一个路由
router.get("/", function(req, res) {
    res.send("开始");
});
router.get("/login", function(req, res) {
    res.render("login");
});
router.post("/login", urlencodedParser, function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    console.log(password);
    var md5 = crypto.createHash("md5");
    md5.update(password);
    var sign = md5.digest("hex");
    console.log(sign);
    user.find({ username: username, password: sign }, function(err, docs) {
        console.log(err);
        console.log(docs);
        if (docs.length > 0) {
            req.session.islogin = true;
            req.session.username = username;
            req.session.userId = docs[0]._id;
            console.log(docs[0]._id);
            res.redirect("/main");
        } else {
            res.send("登录失败");
        }
    });
});
router.post("/register", urlencodedParser, function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    console.log(username);
    console.log(password);
    var md5 = crypto.createHash("md5");
    md5.update(password);
    var sign = md5.digest("hex");
    user.create({
        username: username,
        password: sign
    }, function(err, doc) {
        res.redirect("/login");
    });
});
router.get("/main", urlencodedParser, function(req, res) {
    if (req.session.islogin) {
        var userId = req.session.userId;
        essay.find({ user: userId }, function(err, docs) {
            res.render("main", { essay: docs });
        });
    } else {
        res.redirect("/main");
    }
});
router.post("/add-essay", urlencodedParser, function(req, res) {
    var title = req.body.title;
    var content = req.body.content;
    var userId = req.session.userId;
    console.log(userId);
    essay.create({
            title: title,
            content: content,
            user: userId
        },
        function(err, doc) {
            res.redirect("/main");
        }
    );
})
router.get("/all", urlencodedParser, function(req, res) {
    essay.find({}).populate('user').exec().then(function(docs) {
        res.render("all", { essay: docs });
    })
})
module.exports = router;